<?php 

/**
 * Uploads the files to the temporary directory.
 */
function jnj_deploy_tool_upload_file($form, &$form_state) {
  //create the output dir string based in the settings information
  $output_dir = file_directory_temp() .'/'. //drupal temp dir
                jnj_deploy_tool_get_output_folder_name() .'/'.  //deployment folder
                jnj_deploy_tool_get_site_folder();  //project folder inside the deployment folder
             
  //save the file in the $output_dir
  file_save_upload('jnj_deploy_tool_file_to_upload',
                  array(),
                  $output_dir,
                  FILE_EXISTS_REPLACE);
}

/**
 * Validate if the directory name is valid.
 */
function jnj_deploy_tool_validate_dir_name($name) {
  $regexp = "/^[A-z0-9_-]+$/";
  
  if (preg_match($regexp, $name)) {
    return TRUE;
  }

  return FALSE;
}

/**
 * This function returns TRUE if server is Windows. FALSE otherwise.
 */
function jnj_deploy_tool_server_is_windows() {
  if (stristr(PHP_OS, 'WIN') === FALSE) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

/**
 * Returns an array of directories.
 */
function jnj_deploy_tool_get_dirs($path) {
  $result = array();
  
  if ($handle = opendir($path)) {
    while (false !== ($dir = readdir($handle))) {
      if (is_dir($path .'/'. $dir) && $dir != '.' && $dir != '..') {
        $result[$dir] = $dir;
      }
    }

    closedir($handle);
  }
  
  return $result;
}

/**
 * Return the modules path.
 */
function jnj_deploy_tool_get_modules_path() {
  return 'sites/all/modules';
}

/**
 * Return the themes path.
 */
function jnj_deploy_tool_get_themes_path() {
  return 'sites/all/themes';
}

/**
 * Return the apache custom path.
 */
function jnj_deploy_tool_get_apache_custom_path() {
  $folder = jnj_deploy_tool_get_site_folder();
  $apache_custom_file = "sites/default/$folder.apache_custom";
  
  return $apache_custom_file;
}

/**
 * Return the PHP custom path.
 */
function jnj_deploy_tool_get_php_custom_path() {
  $folder = jnj_deploy_tool_get_site_folder();
  $php_custom_file = "sites/default/$folder.php";
  
  return $php_custom_file;
}

/**
 * Return the flag file.
 */
function jnj_deploy_tool_get_flag_file_path() {
  $folder = jnj_deploy_tool_get_site_folder();
  $flag_file = "sites/default/files/$folder.flag";
  
  return $flag_file;
}
  
/**
 * Return the sql dump path.
 */
function jnj_deploy_tool_get_sql_dump_path() {
  return file_directory_path() .'/backup_migrate/manual/sqldump.sql.gz';
}

/**
 * Return the output folder name.
 */
function jnj_deploy_tool_get_output_folder_name() {
  return variable_get('jnj_deploy_tool_outputdir', 'deploy');
}

/**
 * Return the output path.
 */
function jnj_deploy_tool_get_output_path() {
  $output_dir = file_directory_temp() .'/'. jnj_deploy_tool_get_output_folder_name();
  return $output_dir .'/'. jnj_deploy_tool_get_site_folder();
}

/**
 * Retrieve the site folder name.
 */
function jnj_deploy_tool_get_site_folder() {
  return basename(getcwd());
}

/**
 * Performes an action.
 */
function _jnj_deploy_tool_action($options) {
  $retval = 0;
  $message = $options['message'];

  // Action 'function_mkdir'.
  if ($options['action'] == 'function_mkdir') {
    if (!is_dir($options['targets'][0])) {
      $action = @mkdir($options['targets'][0]);
    }
    else {
      $action = TRUE;
    }
  }
  else {

    // Action 'command_tar'.
    if ($options['action'] == 'command_tar') {
      if (jnj_deploy_tool_server_is_windows()) {
        $command = 'tar --exclude=".svn" -C $0 -c . | tar -C $1 -x';
      }
      else {
        $command = 'tar --exclude=".svn" -cz -C $0 . | tar -C $1 -zx';
      }
    }

      // Action 'command_tar_split'
    elseif ($options['action'] == 'command_tar_split') {
      if (jnj_deploy_tool_server_is_windows()) {
        $command = 'tar -C $0 -c . | gzip | split -b $1k - $2/$3';
      }
      else {
        $command = 'tar -cz -C $0 . | split -b $1k - $2/$3';
      }
    }
    
    // Action 'command_tar_gzip'
    elseif ($options['action'] == 'command_tar_gzip') {
      if (jnj_deploy_tool_server_is_windows()) {
        $command = 'tar -C $0 -c . | gzip $1';
      }
      else {
        $command = 'tar -cz -C $0 . -f $1';
      }
    }
    
    
    // Action 'command_cat'
    elseif ($options['action'] == 'command_cat') {
      $command = 'cat $0/$1* >> $2/merged_$3';
    }

    // Action 'command_cp'.
    elseif ($options['action'] == 'command_cp') {
      $command = 'cp $0 $1';
    }

    // Action 'command_cp_r'.
    elseif ($options['action'] == 'command_cp_r') {
      $command = 'cp -R $0 $1';
    }

    for ($i = count($options['targets']) - 1; $i >= 0; $i--) {
      $command = str_replace('$' . $i, $options['targets'][$i], $command);
    }
    $action = ((system($command, $retval) === FALSE || $retval != 0) ? FALSE : TRUE);
  }

  // Processing action.
  if (!$action) {
    $ok = FALSE;
    drupal_set_message($message . t('<span style="color: red;">FAILED!</span>'));
    watchdog('Deploy-Action', 'Action: '. $options['action'] .' failed! Debug: '. print_r($options, 1));
  } else {
    $ok = TRUE;
    watchdog('Deploy-Action', 'Action: '. $options['action'] .' executed successfully.');
  }
  
  return $ok;
}

/**
 * Create a directory.
 */
function jnj_deploy_tool_create_dir($dir) {
  $options = array(
    'action' => 'function_mkdir',
    'message' => t('Creating directory ') . $dir .'...',
    'targets' => array(
      $dir,
    ),
  );
    
  return _jnj_deploy_tool_action($options);
}

/**
 * Tar a diretory.
 */
function jnj_deploy_tool_tar($from, $to, $type) {
  $options = array(
    'action' => 'command_tar',
    'message' => t('Copying '. $type .' directory to the temporary '. $type .' directory...'),
    'targets' => array(
      $from,
      $to,
    ),
  );
  
  return _jnj_deploy_tool_action($options);
}

/**
 * Tar and zip a diretory.
 */
function jnj_deploy_tool_tar_zip($from, $to) {
  $options = array(
    'action' => 'command_tar_gzip',
    'message' => t('Tar/zip directory ') . $from .'...',
    'targets' => array(
      $from,
      $to,
    ),
  );
  
  return _jnj_deploy_tool_action($options);
}

/**
 * Get all modules except unwanted ones.
 */
function jnj_deploy_tool_get_allowed_modules($dir) {
  // build module section
  $modules = jnj_deploy_tool_get_dirs($dir);
  $unwanted_modules = jnj_deploy_tool_get_unwanted_modules();
  
  // remove unwanted modules from the list
  foreach ($unwanted_modules as $unwanted) {
    foreach ($modules as $key => $module) {
      if ($module == $unwanted) {
        unset($modules[$key]);
        break;
      }
    }
  }
  
  return $modules;
}

/**
 * Executes Backup Migrate module and dumps the database.
 */
function jnj_deploy_tool_backup_database($drupal_sqldump_path, $destination_dir) {
  // Database backup.
  _backup_migrate_dump_tables(
    'sqldump',
    _backup_migrate_default_exclude_tables(),
    _backup_migrate_default_structure_only_tables(),
    'sql',
    'save',
    'gzip',
    'manual',
    FALSE
  );
  
  // if file exists, delete it
  if (file_exists($destination_dir)) {
    $command = 'rm -f '. $destination_dir;
    system($command);
  }

  // Copy backup to the work dir.
  // Here we should use Drupal's configured files directory, because it's the same used
  // by the Backup and Migrate module.
  $options = array(
    'action' => 'command_cp',
    'message' => t('Copying SQL Dump to the work directory... '),
    'targets' => array(
      $drupal_sqldump_path,
      $destination_dir,
    ),
  );
  
  return _jnj_deploy_tool_action($options);
}

/**
 * Delete dir's contents.
 */
function jnj_deploy_tool_delete_dir_contents($dir) {
  $command = "rm -rf $dir/*";
  system($command);
}

/**
 * Alter max_execution_time so the script can have more time to execute it.
 */
function jnj_deploy_tool_set_time_limit() {
  $time = variable_get('jnj_deploy_tool_max_exec_time', '300');
  set_time_limit($time);
}